package common.intercepter;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import common.beans.ResultBean;
import common.beans.User;
import common.intercepter.service.TokenAuthorizingService;
import common.intercepter.service.TsgyunAuthorizingService;
import common.intercepter.service.YuntsgAuthorizingService;
import common.util.CacheUtil;
import common.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@Slf4j
public class Interceptor implements HandlerInterceptor {

    @Resource
    CacheUtil cacheUtil;

    @Resource
    TokenAuthorizingService authService;

    @Resource
    TsgyunAuthorizingService tsgyunAuthSer;

    @Resource
    YuntsgAuthorizingService yuntsgAuthSer;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("当前访问地址:" + request.getRequestURL() + "--host:" + request.getRemoteHost());
        boolean isLogined = false;
        if (System.currentTimeMillis() > 1) {
            // return true;
        }
        String token = request.getHeader("token");
        boolean legalToken = StrUtil.isNotEmpty(token) && !"null".equals(token) && !"undefined".equals(token);
        if (legalToken) {
            log.debug("首先进行Token验证" + token);
            if (authService.decryptToken(token)) {
                log.debug("Token验证成功");
                isLogined = true;
            } /*else {
                returnAjaxResponse(response, "noLogin", 1);
            }*/
        }
//        if (!legalToken) {
//            Cookie[] cookies = request.getCookies();
//            isLogined = tsgyunAuthSer.decryptCookie(cookies);
//            if (!isLogined) {
//                log.info("通过yuntsg的cookie获取的用户");
//                isLogined = yuntsgAuthSer.decryptCookie(cookies);
//            }
//        }
        if (isLogined) {

            User user = (User) cacheUtil.getObject("user");
            //这里授权失败应该跳往无权限页面.
            boolean hasPermission = authService.doGetAuthorizationInfo(user);

            if (hasPermission) {
                log.debug("验证权限有权限");
                UserUtil.setUser(user);
            } else {
                return returnAjaxResponse(response, "noPermission", 2);
            }
        } else {
            return returnAjaxResponse(response, "noLogin", 1);
        }
        log.info("登录成功,返回True");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        UserUtil.clearAllUserInfo();
    }


    private boolean returnAjaxResponse(HttpServletResponse response, String msg, Integer code) {
        //下面是服务器上的部署代码
        ResultBean<Object> result = new ResultBean<Object>();
        result.setCode(code);
        result.setMsg(msg);
        response.setContentType("application/json; charset=utf-8");
        JSONObject jsonObj = JSONUtil.parseObj(JSONUtil.toJsonStr(result));
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(jsonObj.toString());
            log.info("返回是\n");
            log.info(jsonObj.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return false;
    }


}